<?php

namespace app\yperp\logic;

use app\yperp\common\Tools;
use app\yperp\model\Goods;
use app\yperp\model\GoodsSku;
use app\yperp\model\GoodsSkuStandby;
use think\Db;

class Standby
{

    private static $instance;
    protected  $token;
    public static function getInstance()
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    function itemMainImageTo($goods)
    {
        $itemMainImage = json_decode($goods['itemMainImage'], true);
        $header_imgs = [];
        foreach ($itemMainImage as $img) {
            $res = Tools::downImage($img);
            $header_imgs[] = $res['id'];
        }
        return join(',', $header_imgs);
    }

    function itemDetailImagesTo($goods)
    {
        //imageUrl
        $itemDetailImages = json_decode($goods['itemDetailImages'], true);
        $Detail_imgs = [];
        foreach ($itemDetailImages as $img) {
            $res = Tools::downImage($img['imageUrl']);
            $Detail_imgs[] = $res['id'];
        }
        return join(',', $Detail_imgs);
    }

    function sku_remove($ids = [])
    {
        // 启动事务
        Db::startTrans();
        try {
            foreach ($ids as $id) {
                $sku = GoodsSku::where('id', $id)->find();
                if ($sku) {
                    $sku = $sku->toArray();
                } else {
                    continue;
                }
                $goods = Goods::where('itemSpuId', $sku['itemSpuId'])->find();

                $sku['main_img'] = Tools::downImage($sku['pic'])['id'];
                $sku['header_imgs'] = $this->itemMainImageTo($goods);
                $sku['body_imgs'] = $this->itemDetailImagesTo($goods);

                // dump($sku);
                // continue;

                $where = ['supplierId' => $sku['supplierId']];
                unset($sku['id']);
                $standby = GoodsSkuStandby::where($where)->find();
                if ($standby) {
                    $standby = GoodsSkuStandby::where($where)->update($sku);
                } else {
                    $standby = GoodsSkuStandby::create($sku);
                }
            } // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            dump($e->getMessage());
            dump($e->getTraceAsString());
        }
    }
}
